import Taro, { useDidHide, useDidShow, useReady } from "@tarojs/taro";
import { View } from "@tarojs/components";
import {
  C05CustomerService,
  C29UserOverview,
  C43Notification,
  Layout,
} from "@/components";
import {
  useUserInfo,
  getUserData,
  getUserPageData,
  acceptGift,
  snoozeLineUpNotification,
} from "@/store/userDataContext";
import { useEffect, useLayoutEffect, useState } from "react";
import { useAuth } from "@/store/authContext";
import style from "./index.module.scss";
import { ModalTypes, useApplicationInfo } from "@/store/applicationDataContext";
import { navigateTo } from "@/utils/navigation";
import {
  ApiEventOnlyMapping,
  GiftPayloadShape,
  LineUpPayloadShape,
} from "@/data/user/userTypes";
import { ApiItemTypeMapping } from "@/data/shared/entityShapes";
import { isEqual } from "lodash-es";
import { ActionNames, sendAction } from "@/utils/tracking";

const generateNavigationLink = (eventType: ApiEventOnlyMapping) => {
  switch (eventType) {
    case ApiItemTypeMapping.Course:
      return "pages/course-detail/index?id=";
    case ApiItemTypeMapping.CourseDiscovery:
      return "pages/bundlecourse-detail/index?id=";
    case ApiItemTypeMapping.Talk:
      return "pages/talk-detail/index?id=";
    case ApiItemTypeMapping.Exhibition:
      return "pages/exhibition-detail/index?id=";
  }
};

function User() {
  const { userInfoState, dispatchUserDataAction } = useUserInfo();
  const { userData, userPageData } = userInfoState;
  const { dispatchAuthAction } = useAuth();
  const { dispatch } = useApplicationInfo();
  const [filteredGiftNotifications, setfilteredGiftNotifications] = useState<
    GiftPayloadShape[]
  >([]);
  const [filteredQueueNotifications, setFilteredQueueNotifications] =
    useState<LineUpPayloadShape>([]);

  useDidShow(() => {
    sendAction(ActionNames.MyListImpression, null);
    getUserData(dispatchUserDataAction, userData!, {
      authDispatch: dispatchAuthAction,
    });
    if (!userPageData) {
      getUserPageData(dispatchUserDataAction);
    }
  });

  useEffect(() => {
    if (userData) {
      setfilteredGiftNotifications(userData.userInfo.noGetAppoinment);
      setFilteredQueueNotifications(userData.userInfo.lineUpResponses);
    }
  }, [userData!.userInfo]);

  const removeFromQueueList = async (id) => {
    const snoozed = await snoozeLineUpNotification({
      query: { lineUpId: id },
      authDispatch: dispatchAuthAction,
    });
    if (snoozed) {
      setFilteredQueueNotifications((prevList) =>
        prevList.filter((prevListItem) => id !== prevListItem.lineUpId)
      );
    }
  };

  return (
    <Layout>
      {userData && userPageData && (
        <View className={style["user-page-wrapper"]}>
          <View className={style["notification-list-placement"]}>
            {filteredGiftNotifications.map((giftedEvent) => {
              const removeFromGiftList = () => {
                setfilteredGiftNotifications((prevList) =>
                  prevList.filter(
                    (prevListItem) =>
                      !isEqual(
                        giftedEvent.orderInfoIds,
                        prevListItem.orderInfoIds
                      )
                  )
                );
              };
              return (
                <C43Notification
                  key={giftedEvent.orderInfoIds.join("-")}
                  notificationType={"gift-event"}
                  name={giftedEvent.name}
                  eventType={giftedEvent.type}
                  modalOpeningCb={() => {
                    dispatch({
                      type: "SHOW_DATA_MODAL",
                      data: {
                        modal: ModalTypes.GiftedEvent,
                        title: "您被赠予了一节课程！",
                        name: giftedEvent.name,
                        content: giftedEvent.appointmentSchedulings.map(
                          (scheduling) => ({
                            name: scheduling.name,
                            timeInfo: {
                              date: scheduling.schedulingDate,
                              startTime: scheduling.schedulingStartTime,
                              endTime: scheduling.schedulingEndTime,
                            },
                          })
                        ),
                        primaryCta: {
                          text: "确认接受",
                          callback: () => {
                            acceptGift({
                              query: { orderInfoIds: giftedEvent.orderInfoIds },
                              authDispatch: dispatchAuthAction,
                            });
                            removeFromGiftList();
                          },
                        },
                        bottomText: [
                          "您接受后，可在“个人中心 — 我的课程” 中查看",
                        ],
                      },
                    });
                  }}
                  closeCb={() => {
                    removeFromGiftList();
                  }}
                />
              );
            })}
            {filteredQueueNotifications.map((emptySpotData) => {
              return (
                <C43Notification
                  key={emptySpotData.mainId}
                  notificationType={"queue-spot-ready"}
                  name={emptySpotData.name}
                  eventType={emptySpotData.mainType}
                  modalOpeningCb={() => {
                    dispatch({
                      type: "SHOW_DATA_MODAL",
                      data: {
                        modal: ModalTypes.WaitingListReady,
                        title: "以下课程可预约：",
                        name: emptySpotData.name,
                        primaryCta: {
                          text: "去预约",
                          callback: () => {
                            navigateTo(
                              `${generateNavigationLink(
                                emptySpotData.mainType
                              )}${emptySpotData.mainId}`
                            );
                          },
                        },
                        secondaryCta: {
                          text: "不再提示",
                          callback: () => {
                            removeFromQueueList(emptySpotData.lineUpId);
                          },
                        },
                        bottomText: [
                          "选择“不再提示”后，",
                          "可在“个人中心 — 我的等候列表”中查看",
                        ],
                      },
                    });
                  }}
                  closeCb={() => {
                    removeFromQueueList(emptySpotData.lineUpId);
                  }}
                />
              );
            })}
          </View>
          <C29UserOverview
            userData={userData}
            backgroundImageUrl={userPageData.topBackgroundImage}
          />
        </View>
      )}
      <C05CustomerService />
    </Layout>
  );
}

export default User;
